import tkinter
import cv2
import numpy as np
import tkinter as tk
from tkinter import scrolledtext
import time

output_width = 218
output_height = 64

def get_char(luminance)->str:
    chars = "@#%!+=_&*$?:"
    return chars[int((luminance/255.0)*(len(chars)-1))]

def video_to_ascii(video_path,output_width,output_height):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise IOError("Error opening video file")
    fps = cap.get(cv2.CAP_PROP_FPS)
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    print(f"FPS:{fps},Frame Count:{frame_count}")
    print(f"Output height:{output_height}")
    return cap

def window_init(width : int,height : int)->tk:
    root = tk.Tk()
    root.title("Video to ASCII Art")
    root.geometry(f"{width*10}x{height*16}")
    return root



def window_update(window:tk)->int:
    video_path = "ss.mp4"
    cap = video_to_ascii(video_path,output_width,output_height)
    while True:
        ret,frame = cap.read()
        if not ret:
            break
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        resized = cv2.resize(gray,(output_width,output_height),interpolation=cv2.INTER_LINEAR)
        
        ascii_frame = ""
        for row in resized:
            for luminance in row:
                ascii_frame += get_char(luminance)
            ascii_frame += "\n"
        text.delete(1.0,tk.END)
        text.insert(tk.END,ascii_frame)
        time.sleep(1/int(cap.get(cv2.CAP_PROP_FRAME_COUNT)))
        window.update()
    cap.release()
    return 0
    

if __name__ == "__main__":
    window = window_init(output_width,output_height)
    text = tk.Text(window,height = int(output_height*1.1),width = int(output_width*1.6))
    text.pack()
    window_update(window)
    window.mainloop()
